package com.ruoyi.activiti.listener;

import com.ruoyi.activiti.mapper.TaskMapper;
import com.ruoyi.activiti.service.IBizExamService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import lombok.AllArgsConstructor;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.persistence.entity.IdentityLinkEntity;
import org.activiti.engine.task.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@AllArgsConstructor
public class UserDepartmentLeaderListener implements TaskListener , ExecutionListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        String applyUserId = (String) delegateTask.getVariable("applyUserId");
        String userDeptLeaderRole = null;
        Set<IdentityLink> identityLinkEntity = delegateTask.getCandidates();
        for(IdentityLink o:identityLinkEntity){
            userDeptLeaderRole = o.getGroupId();
        }
        TaskMapper taskMapper = SpringUtils.getBean("taskMapper");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<String> assigneeList = taskMapper.selectUserDeptLeaderByUsername(applyUserId,userDeptLeaderRole);
//        for(String str:assigneeList){
//            System.out.println(str);
//        }
        if(assigneeList.size()==1){
            taskService.setAssignee(delegateTask.getId(),assigneeList.get(0));
        }
        delegateTask.deleteCandidateGroup(userDeptLeaderRole);
//        delegateTask.setVariable("deanLeader",assigneeList.get(0));

    }

    @Override
    public void notify(DelegateExecution delegateExecution) {
//        System.out.println(delegateExecution.getVariable("applyUserId"));
    }
}
